package com.smalls.newvideotwo.util;

import android.util.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by thearyong on 2017/1/20.
 * </p>
 */

public class EncodeUtils {
    /**
     * 经MD5把字符串散列成一个32位散列值
     */
    public static String md5(String toencode) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(toencode.getBytes());
            return hex(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return toencode;
    }

    public static String hex(byte[] toencode) {
        StringBuilder sb = new StringBuilder(toencode.length * 2);
        for (byte b : toencode) {
            sb.append(Integer.toHexString((b & 0xf0) >>> 4));
            sb.append(Integer.toHexString(b & 0x0f));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 对字符串Base64编码
     */
    public static String encodeBase64(String value) {
        return new String(Base64.encode(value.getBytes(), Base64.URL_SAFE|Base64.NO_WRAP));
    }

    /**
     * 对base64编码字符串解码
     */
    public static String decodeBase64(String base64) {
        return new String(Base64.decode(base64.getBytes(), Base64.DEFAULT));
    }

    /**
     * 对二进制数据base64编码
     */
    public static String encodeBase64(byte[] buffer) {
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /**
     * auth_key AES加密
     */
    public static String AES(String key, String sSrc) {
        try {
            if (key == null) {
                System.out.println("sztw3a Authorize API key is null");
                return null;
            }
            if (key.length() != 16) {
                System.out.println("sztw3a Authorize API key is not 16 byte");
            }
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            String encryptedStr = EncodeUtils.encodeBase64(encrypted);
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(encryptedStr);
            return m.replaceAll("");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 数字与大写字母混编字符串
     * @param size
     * @return
     */
    public static String getNumLargeLetter(int size){
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for(int i=0; i<size;i++){
            if(random.nextInt(2) % 2 == 0){//字母
              buffer.append((char) (random.nextInt(27) + 'A'));
            }else{//数字
            buffer.append(random.nextInt(10));
            }
        }
        return encodeBase64(buffer.toString());
    }

    /**
     * 数字与大写字母混编字符串
     * @param size
     * @return
     */
    public static String getNumber(int size){
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for(int i=0; i<size;i++){
            buffer.append(random.nextInt(10));
        }
        return buffer.toString();
    }

    /***
     特殊含义                                                            十六进制值
     1.+ 表示空格（在 URL 中不能使用空格）           %20
     2./ 分隔目录和子目录                                     %2F
     3.? 分隔实际的 URL 和参数                             %3F
     4.% 指定特殊字符                                         %25
     5.# 表示书签                                               %23
     6.& URL 中指定的参数间的分隔符                     %26
     7.= 等于号                                                  %3D
     */
    public static String procStr(String str) {
        String newStr = new String(str);
        ////replaceAll的结果，存在返回的串中，原串不变啊啊啊啊
        return newStr.replaceAll("=","%3D").replaceAll("[+]","%20").
                replaceAll("/","%2F").replaceAll("[?]","%3F").replaceAll("#","%23").replaceAll(" ","%20");
    }

    public static void main(String[] args) {
        String nns_auth = AES("8um551dtObtmHdvx", "8um551dtObtmHdvx"
                + "$$" + "10092"
                + "$$" + "8851004255841640"
                + "$$" + "Maij2018091205971064"
                + "$$" + "20170921143227");
        System.out.println(nns_auth);
    }


}
